package com.example.jasonrpc.server.simple;

import com.example.jasonrpc.common.ReflectionUtils;
import com.example.jasonrpc.proto.Request;
import com.example.jasonrpc.proto.ServiceDescriptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 管理rpc暴露的服务
 */
public class ServiceManager {
    private static final Logger log = LoggerFactory.getLogger(ServiceManager.class);
    private Map<ServiceDescriptor, ServiceInstance> services;

    public ServiceManager() {
        this.services = new ConcurrentHashMap<>();
    }

    public <T> void register(Class<T> interfaceClass, T bean) {
        Method[] methods = ReflectionUtils.getPublicMethods(interfaceClass);
        for (Method method : methods) {
            ServiceInstance instance = new ServiceInstance(bean, method);
            ServiceDescriptor serviceDescriptor = ServiceDescriptor.build(interfaceClass, method);
            services.put(serviceDescriptor, instance);
            log.info("register service: " + serviceDescriptor.getClazz()
                    + " , " + serviceDescriptor.getMethod());
        }
    }

    public ServiceInstance lookUp(Request request) {
        ServiceDescriptor descriptor = request.getService();
        return services.get(descriptor);
    }

    public List<String> getRegisterServices() {
        List<String> serviceClassName = new ArrayList<>();
        for (ServiceDescriptor descriptor : services.keySet()) {
            serviceClassName.add(descriptor.getClazz());
        }
        return serviceClassName;
    }
}
